package com.qingzhu;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.pojo.Login;
import com.qingzhu.pojovo.ResultVo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServer implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        ObjectMapper objectMapper = new ObjectMapper();

        // 获取项目域中储存的人员信息
        ServletContext servletContext = request.getServletContext();
        Login login = (Login) servletContext.getAttribute("login");
        if (login != null) {
            filterChain.doFilter(request,response);
        }else {
            String requestURI = request.getRequestURI();
            if (requestURI != null && requestURI.split("/").length > 1) {
                String serverName = requestURI.split("/")[1];
                // 如果请求的是以下服务之一，则必须是以登录的状态才能成功
                boolean isPay = serverName.equals("pay");
                boolean isOrder = serverName.equals("order");
                boolean isUser = serverName.equals("user");
                boolean isReceiving = serverName.equals("receiving");
                if (isPay || isOrder || isUser || isReceiving) {
                    System.out.println("检测到当前用户没有登录，请求被拒绝！");
                    response.getWriter().write(objectMapper.writeValueAsString(new ResultVo(1003,"用户未登录，请求被拒接！")));
                }else {
                    System.out.println("检测到当前用户没有登录，但是请求的服务允许被访问..");
                    filterChain.doFilter(request,response);
                }
            }else {
                System.out.println("检测到没有请求任何服务..");
                filterChain.doFilter(request,response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
